﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Runtime.Remoting.Messaging;

namespace ConsoleApplication1.TestThread
{
    public  class Thread1
    {
        public class Preson
        {
            public string name;
            public int age;
        }

        delegate string myName(string name);
        public static void Main()
        {
            ThreadMessage("main Thread");

            myName myxx = new myName(Hello);
            //IAsyncResult result = myxx.BeginInvoke("李世杰", null, null);

            //while (!result.IsCompleted)
            //{
            //    Thread.Sleep(200);
            //    Console.WriteLine("mainThread do work");
            //}

            //while (!result.AsyncWaitHandle.WaitOne(200))
            //{
            //    Console.WriteLine("mainThread do work");
            //}

            //WaitHandle[] whList = new WaitHandle[] {result.AsyncWaitHandle };
            //while (!WaitHandle.WaitAll(whList, 200))
            //{
            //    Console.WriteLine("main Thread do work");
            //}

            //string endResult = myxx.EndInvoke(result);
            //Console.WriteLine(endResult);

            Preson p = new Preson();
            p.name = "小李";
            p.age = 1;

            myxx.BeginInvoke("李世杰",new AsyncCallback(Completed),p);

            for (int i = 0; i < 6; i++)
            {
                Console.WriteLine("mainThread do work");
            }

            Console.ReadKey();
        }

        static string Hello(string name)
        {
            ThreadMessage("Async Thread");
            Thread.Sleep(2000);
            return "Hello" + name;
        }

        static void ThreadMessage(string data)
        {
            Console.WriteLine(string.Format("{0} ThreadID is :{1}",data,Thread.CurrentThread.ManagedThreadId));
        }

        static void Completed(IAsyncResult result)
        {
            ThreadMessage("Async Completed");
            AsyncResult ar = (AsyncResult)result;
            myName mydelege = (myName)ar.AsyncDelegate;
            string endResult = mydelege.EndInvoke(ar);

            Preson p = (Preson)result.AsyncState;
            

            Console.WriteLine(endResult+"\n"+p.name+"'s age is "+p.age);
        }
        

    }
}
